import BaseInput from "@/components/base/Input"
import { Props, Reg } from "@/components/form_item/formItemConfig"
import { selectedAmountAtom } from "@/pages/UserCenterPage/atom"
import { createLogger } from "@/utils/logger"
import styled from "@emotion/styled"
import { useAtom } from "jotai"
import { forwardRef, useEffect, useImperativeHandle, useState } from "react"
import { useFormContext } from "react-hook-form"
import Svg from "../base/Svg"

const logger = createLogger("InputMoneyText")

export type TypeInputMoneyTextRef = {
    setCustomValue: (v: string | undefined) => void
}

const InputMoneyText = forwardRef<TypeInputMoneyTextRef, Props>(
    (
        {
            fieldName,
            initValue,
            errorRegMsg,
            placeholder,
            isInputPlaceholder = true,
            required,
            showPlaceholder = true,
            iconSrc, // 新增：传入图标
            min, // 新增：最小值
            max = 100000000, // 新增：最大值
            className = "",
            style,
            customText,
            customOnClick,
            showClear = true,
        },
        ref,
    ) => {
        const [selectedAmount, setSelectedAmount] = useAtom(selectedAmountAtom)
        const methods = useFormContext()
        const {
            register,
            resetField,
            clearErrors,
            setValue: setAmount,
            watch,
            formState,
            getFieldState,
            setError,
        } = methods
        const [rule, setRule] = useState<{
            len: boolean
            ruleReg: boolean
        }>({
            len: false,
            ruleReg: false,
        })
        const Clear = () => {
            clearErrors(fieldName)
            setAmount(fieldName, null)
            setSelectedAmount(null)
            resetField(fieldName)
        }
        const values = watch(fieldName) ?? initValue
        const errorsName = formState.errors[fieldName]
        const FieldState = getFieldState(fieldName, formState)
        const [isOutOfRange, setIsOutOfRange] = useState(false)
        const [isInteracted, setIsInteracted] = useState(false) // 是否已输入
        useEffect(() => {
            if (!isInteracted) return //初次加载进来不触发校验
            let _rule = rule
            let outOfRange = false // 是否超出 min/max
            if (values && Reg.depositReg.test(values)) {
                _rule = {
                    ..._rule,
                    ...{ ruleReg: true },
                }
            } else {
                _rule = {
                    ..._rule,
                    ...{ ruleReg: false },
                }
                setError(fieldName, {
                    message: errorRegMsg || "Amount 100-500,000",
                    type: "pattern",
                })
            }
            if (min !== undefined && values < min) {
                setError(fieldName, { message: `Minimum value is ${min}`, type: "min" })
                outOfRange = true
            } else if (max !== undefined && values > max) {
                setError(fieldName, { message: `Maximum value is ${max}`, type: "max" })
                outOfRange = true
            } else {
                clearErrors(fieldName)
            }
            setIsOutOfRange(outOfRange)
            setRule(_rule)
            // eslint-disable-next-line react-hooks/exhaustive-deps
        }, [values])
        // const showError = (errorsName?.message || !rule.ruleReg || !rule.len) && FieldState.isDirty
        const showError = errorsName?.message && FieldState.isDirty
        useImperativeHandle(ref, () => ({
            setCustomValue: (value: string | undefined) => {
                setAmount(fieldName, value)
            },
        }))
        const renderIcon = () => {
            if (typeof iconSrc === "string") {
                return <InputIcon src={iconSrc} />
            }
            if (typeof iconSrc === "object" && iconSrc !== null) {
                return <SvgIconWrapper>{iconSrc as React.ReactElement}</SvgIconWrapper>
            }
            return null
        }

        return (
            <>
                <InputItem
                    className={`
                    ${showError ? " error " : " "} 
                    ${values! ? " showClearIcon " : ""}
                    ${!isInputPlaceholder && showPlaceholder ? " placeholderBox " : ""}
                    ${className || ""}
                    ${isInputPlaceholder ? "inputPlaceholder" : ""}
                `}
                >
                    {iconSrc && renderIcon()}
                    <BaseInputs
                        id={"inputText-" + fieldName}
                        type="number"
                        style={style}
                        maxLength={6}
                        value={values}
                        placeholder={isInputPlaceholder ? placeholder : ""}
                        {...register(fieldName, {
                            required: {
                                message: `${fieldName} is required`,
                                value: required ?? true,
                            },
                            pattern: {
                                value: /^\d+$/,
                                message: "Only numbers are allowed",
                            },
                            maxLength: {
                                value: 6,
                                message: "Text maxLength is 6",
                            },
                            min: min
                                ? {
                                      value: min,
                                      message: `Minimum value is ${min}`,
                                  }
                                : undefined,
                            max: max
                                ? {
                                      value: max,
                                      message: `Maximum value is ${max}`,
                                  }
                                : undefined,
                            onChange: (e) => {
                                setAmount(fieldName, e.target.valueAsNumber || "")
                                setIsInteracted(true) //输入后才校验
                            },
                            onBlur: () => {
                                if (!isInteracted) return //如果用户没有输入，失焦时不触发校验
                                if (!values) clearErrors(fieldName) // 如果清空，则恢复初始状态
                            },
                        })}
                    />
                    {!isInputPlaceholder && showPlaceholder && (
                        <InputLabel
                            className="inputTitle"
                            htmlFor={"inputText-" + fieldName}
                        >
                            {placeholder ?? "Enter Text"}
                        </InputLabel>
                    )}
                    {customText && (
                        <CustomButton
                            className={showClear ? "CustomAndClear" : ""}
                            onClick={customOnClick}
                        >
                            {customText}
                        </CustomButton>
                    )}
                    {showClear && (
                        <CleanInputBox
                            className="cleanIcon"
                            onClick={Clear}
                        >
                            {showError ? (
                                <Svg src={"components/form_item/clear_text_red_icon.svg"} />
                            ) : (
                                <Svg src={"components/form_item/clear_text_icon.svg"} />
                            )}
                        </CleanInputBox>
                    )}
                    {/*{errorsName && <VerifyMessage>{errorsName?.message as string}</VerifyMessage>}*/}
                </InputItem>
                <VerifyMessage className={`${showError ? "stepNextvm" : ""}`}>
                    <em>
                        <Svg src={"components/form_item/public_fail_icon.svg"} />
                    </em>
                    {errorsName?.message as string}
                </VerifyMessage>
            </>
        )
    },
)

export default InputMoneyText

const InputItem = styled.div`
    position: relative;
    display: flex;
    align-items: center;
    border: 1rem solid #bbbdcc;
    border-radius: 8rem;
    background-color: #f3f3f7;
    width: 100%;
    margin-bottom: 10rem;
    &:focus-within {
        border-color: #005ae0; // focus 时边框颜色
    }

    &.showClearIcon span {
        display: inline-block;
    }

    &.showClearIcon .inputTitle {
        //top: 0;
        top: 8rem;
        font-size: 12rem;
        line-height: 16rem;
        color: #6a7081;
    }

    &.inputPlaceholder {
    }

    &.placeholderBox {
        background-color: #ffffff;
    }

    &.placeholderBox input {
        //height: 56rem;
        padding-top: 24rem;
    }

    &.placeholderBox input:focus + label,
    &.placeholderBox.showClearIcon .inputTitle {
        top: 8rem;
        //top: 0;
    }

    &.error p {
        display: block;
    }

    &.error {
        border-color: #fb2d60; // 错误状态边框颜色
    }

    &.error input {
        background-color: #fee0e7;
    }

    &.error label.inputTitle {
        color: #fb2d60;
    }
`

const BaseInputs = styled(BaseInput)`
    flex: 1;
    background-color: #f9f9fb;
    outline: none;
    border-radius: 8rem;
    border: none;
    height: 48rem;
    width: 100%;
    color: #131416;
    //font-family: Inter;
    font-family: "Gilroy", sans-serif;
    font-weight: 500;
    font-size: 20rem;
    line-height: 32rem;
    letter-spacing: 0;
    padding-left: 48rem;

    &:focus {
        outline: none;
        border-color: #165dff;
    }

    &:focus + label {
        //top: 0;
        top: 8rem;
        font-size: 12rem;
    }
    &::placeholder {
        font-family: "Gilroy", sans-serif;
        font-weight: 400;
        font-size: 16rem;
        line-height: 24rem;
        letter-spacing: 0;
        color: #9fa7bc;
        height: 24rem;
    }
`

const InputIcon = styled.img`
    position: absolute;
    left: 12rem;
    width: 24rem;
    height: 24rem;
`
const SvgIconWrapper = styled.div`
    position: absolute;
    left: 12rem;
    width: 24rem;
    height: 24rem;
`
const InputLabel = styled.label`
    position: absolute;
    left: 48rem;
    //top: 18.5rem;
    top: 15.5rem;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 16rem;
    letter-spacing: 0;
    color: #9ca3b4;
    transition:
        top 0.18s linear,
        font-size 0.18s linear;
`

const CustomButton = styled.em`
    position: absolute;
    right: 16rem;
    z-index: 10;
    font-style: normal;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 14rem;
    line-height: 20rem;
    letter-spacing: 0;
    text-align: right;
    vertical-align: middle;
    color: #ff3568;
    &.CustomAndClear + .cleanIcon {
        right: 106rem;
    }
`

const CleanInputBox = styled.span`
    display: none;
    position: absolute;
    top: 12rem;
    //top: 16rem;
    right: 16rem;
    z-index: 10;
    width: 24rem;
    height: 24rem;
    line-height: normal;
    text-align: center;
    transition: opacity 0.3s ease;
`

const VerifyMessage = styled.p`
    display: none;
    position: absolute;
    bottom: -32rem;
    left: 0;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    color: #fb2d60;
    padding-left: 20rem;

    & > em {
        position: absolute;
        display: block;
        width: 16rem;
        height: 16rem;
        top: 0;
        left: 0;
        line-height: normal;
        text-align: center;
    }

    &.stepNextvm {
        display: block;
        position: initial;
        margin: 0;
        padding: 0;
        line-height: 18rem;
        overflow: hidden;
    }
    &.stepNextvm > em {
        position: initial;
        float: left;
        margin-right: 5rem;
    }

    &.stepNextvm::before {
        display: none;
    }

    &.codemsg {
        position: relative;
        margin: 0;
        bottom: -4rem;
        left: 0;
    }

    &.codemsg.error {
        display: block;
    }
`
